﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace CleanFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("DELETE files of special path and pattern, which modified before spcial hours.");
                Console.WriteLine("Usage: {0} <Path> <Pattern> <Hours>", Process.GetCurrentProcess().MainModule.ModuleName);
                return;
            }

            var path = args[0];
            var pattern = args[1];

            var hours = 100;
            if (!int.TryParse(args[2], out hours))
            {
                Console.WriteLine("Invalid <Hours> value.");
                return;
            }

            Console.WriteLine("Ready to delete files of [{1}\\{2}], which modified before {0} hour(s) ...", hours, path, pattern);
            try
            {
                CleanFile(path, pattern, -hours);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured: {0}", ex.Message);
            }

            Console.WriteLine("Finished.");
            return;
        }

        private static void CleanFile(string path, string pattern, int hours)
        {
            DirectoryInfo di = new DirectoryInfo(path);

            FileInfo[] files = di.GetFiles(pattern);
            foreach(var f in files)
            {
                if (f.LastWriteTime < DateTime.Now.AddHours(hours))
                {
                    Console.Write("{0} Delete", f.FullName);
                    f.Delete();
                    Console.WriteLine(" OK");
                }
            }

            // 嵌套遍历所有子目录
            //DirectoryInfo[] dirs = di.GetDirectories();
            //foreach(var d in dirs)
            //{
            //    CleanFile(d.FullName, pattern, hours);
            //}
        }

    }
}
